package com.hengjun.baccarat;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hengjun.baccarat.net.Server;
import com.hengjun.baccarat.net.UpdateManager;
import com.hengjun.baccarat.net.UrlConn;
import com.hengjun.baccarat.pojo.GlobalService;
import com.hengjun.baccarat.utils.BcSysUser;
import com.hengjun.baccarat.utils.ThreadManager;

public class Login extends Activity {
	private EditText accountText;
	private EditText passwordText;
	private Button loginButton;
	private String account;
	private String password;

	private TextView versionCode;
	private ProgressDialog dialog = null;
	public static boolean con = false;
	private Thread thread;
	private UpdateManager update = new UpdateManager(this);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		ThreadManager.handler = new testHander();
		initView();
	}

	private void initView() {
		accountText = (EditText) findViewById(R.id.numberText);
		passwordText = (EditText) findViewById(R.id.passwordText);
		versionCode = (TextView) findViewById(R.id.versionCode);
		versionCode.setText(getVersionName());

		loginButton = (Button) findViewById(R.id.loginButton);
		loginButton.setOnClickListener(new LoginListener());
		handler.obtainMessage(3).sendToTarget();
		update.checkUpdate();//检查更新
	}
	private InputMethodManager inputManager;
	public void loginLayoutClick(View v){
		inputManager = (InputMethodManager) getSystemService(Activity_Map.INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(accountText.getWindowToken(), 0);
		inputManager.hideSoftInputFromWindow(passwordText.getWindowToken(), 0);
	}

	private String getVersionName() {
		String versionName = null;
		try {
			PackageManager pm = this.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(this.getPackageName(), 0);
			versionName = pi.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return versionName;
	}
	private Dialog errorDialog = null;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == 0) {
				Toast.makeText(Login.this, "賬戶或密碼錯誤!", Toast.LENGTH_LONG)
						.show();
			} else if (msg.what == 1) {
				try {
					dialog = createProgressDialog(Login.this, "正在登陸");
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (msg.what == 2) {
				try {
					if (dialog != null) {
						dialog.dismiss();
					}
					if (exitDialog != null) {
						exitDialog.dismiss();
					}
					if (errorDialog != null) {
						errorDialog.dismiss();
					}
					if (userError != null) {
						userError.dismiss();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (msg.what == 3) {
				if (isNetworkConnected(Login.this) == false) {
					Toast.makeText(Login.this, "當前無網絡連接!", Toast.LENGTH_SHORT)
							.show();
				}
			} else if (msg.what == 4) {
				if (dialog != null) {
					dialog.dismiss();
				}
				errorDialog = new Dialog(Login.this, R.style.MyDialogStyle);
				errorDialog.setContentView(R.layout.erro_dialog);
				Button exit = (Button) errorDialog.findViewById(R.id.button1);
				exit.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						errorDialog.dismiss();
					}
				});
				errorDialog.show();
			}
		}
	};

	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				handler.obtainMessage(1).sendToTarget();
				String a;
				a = UrlConn.LoginConnection(account, password);
				if (a.equals("")) {
					handler.obtainMessage(0).sendToTarget();
					handler.obtainMessage(2).sendToTarget();
				} else {
					try {
						GlobalService.list = UrlConn.RecordConn();
						Server.SERVER.connecttoserver(BcSysUser
								.getbcSysUser().getUserIndex() + "");
						Server.SERVER.isOpened();
						Intent intent = new Intent(Login.this, OrderList.class);
						Login.this.startActivity(intent);
						Login.this.finish();
					} catch (Exception e) {
						e.printStackTrace();
						handler.obtainMessage(2).sendToTarget();
					}
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				handler.obtainMessage(4).sendToTarget();
			}
		}
	};

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		update.closeUpdate();
		handler.obtainMessage(2).sendToTarget();
	}

	private class LoginListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			account = accountText.getText().toString();
			password = passwordText.getText().toString();
			if (account.equals("") || password.equals("")) {
				Toast.makeText(Login.this, "請輸入賬戶/密碼", Toast.LENGTH_LONG)
						.show();
			} else {
				if (isNetworkConnected(Login.this) == true) {
					thread = new Thread(runnable);
					thread.start();
				} else {
					handler.obtainMessage(3).sendToTarget();
				}
			}

		}
	}

	public boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}
	private Dialog exitDialog = null;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 是否触发按键为back键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitDialog = new Dialog(this, R.style.MyDialogStyle);
			exitDialog.setContentView(R.layout.exit_dialog);
			Button detemind = (Button) exitDialog.findViewById(R.id.detemind);
			detemind.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					exitDialog.dismiss();
					Login.this.finish();
					android.os.Process.killProcess(android.os.Process.myPid());
					System.exit(0);
				}
			});
			Button cancel = (Button) exitDialog.findViewById(R.id.cancel);
			cancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					exitDialog.dismiss();
				}
			});
			exitDialog.show();
			return true;
		}
		return false;
	}
	private Dialog userError = null;
	@SuppressLint("HandlerLeak")
	private class testHander extends Handler {
		@SuppressLint("HandlerLeak")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == 0) {
				userError = new Dialog(Login.this, R.style.MyDialogStyle);
				userError.setContentView(R.layout.erro_dialog);
				ImageView image = (ImageView) userError
						.findViewById(R.id.imageView1);
				image.setImageResource(R.drawable.confirm_dialog_failweb);
				TextView message = (TextView) userError
						.findViewById(R.id.textView1);
				message.setText("退出提示,賬戶異地登陸!");
				Button exit = (Button) userError.findViewById(R.id.button1);
				exit.setText("退出");
				exit.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						userError.dismiss();
						Intent _intent = new Intent(Login.this, Login.class);
						Login.this.startActivity(_intent);
						Login.this.finish();
					}
				});
				userError.show();
			}
			// 更新
			if (msg.what == 1001) {
				update.showNoticeDialog();//显示更新的对话框
			}
		}
	}

	public static ProgressDialog createProgressDialog(Context context,
			String msg) {
		final ProgressDialog dialog = new ProgressDialog(context);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		dialog.setContentView(R.layout.loading);
	
		TextView message = (TextView) dialog.findViewById(R.id.msg);
		message.setText(msg);
		return dialog;
	}
}
